$(function(){
    paginationInit();
});

var paginationMaxLength=8;//分页栏的最大显示条数
var onlyOnePageIsShow = true;//只有一页的时候是否显示
function paginationInit(){
    $('[am-pagination =pagination_new ]').each(function(){
        initPagination($(this));
    });
}

function initPagination(element){

    element.html('');
    var pagenumber = element.attr('pagenumber');
    var totalpage = element.attr('totalpage');
    var pMaxLength = element.attr('paginationMaxLength');
    var onePageIsShow = element.attr('onlyOnePageIsShow');
    // console.log(totalpage)
    if(isNeedPagination(Number(totalpage),onePageIsShow)){
        var content = '<ul class="am-pagination am-pagination-centered"><li value="0"><a href="javascript:void(0);">«</a></li>';
        for(var i =1; i<=totalpage;i++){
            content +='<li value="'+i+'"><a href="javascript:void(0);">'+i+'</a></li>'
        }
        content +='<li value="-1"><a href="javascript:void(0);">»</a></li></ul>';
        element.append(content);
        element.children('ul').children('li[value='+pagenumber+']').attr('class','am-active');
        setDisplayMaxLength(element,pMaxLength);
        addClickListener(element);
    }
}

function setDisplayMaxLength(element,len){
    var currentpage =  Number(element.attr('pagenumber'));
    var totoalpage = Number(element.attr('totalpage'));
    if(checkParamIsPositiveInteger(len)){
        len = Number(len);
    }else{
        len =paginationMaxLength;
    }
    if(len<totoalpage){
        var temp1 = parseInt((len-1)/2);
        var temp2 = parseInt(len/2);
        if(temp1<temp2){
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1 + 1;
        }else{
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1;
        }
        if(leftstart<1){
            rightend +=(1-leftstart);
            leftstart = 1;
        }
        if(rightend>totoalpage){
            if(leftstart>1){
                leftstart -=(rightend-totoalpage);
            }
            rightend =totoalpage;
        }
        if(leftstart<1){
            leftstart=1
        }
        while(leftstart >1){
            element.children('ul').children('li[value = '+(--leftstart)+']').css('display','none');
        }
        while(rightend <totoalpage){
            element.children('ul').children('li[value = '+(++rightend)+']').css('display','none');
        }
    }
}

function isNeedPagination(totalpage,settingfromHTML){
    var condition ;
    if(settingfromHTML == "true"){
        condition = true;
    }else if(settingfromHTML == 'false'){
        condition = false;
    }else {
        condition = onlyOnePageIsShow;
    }
    if(condition && totalpage<1){
        return false;
    }else if(!condition && totalpage<=1){
        return false;
    }
    return true;
}
//根据页面pagenumber、my_totoalpage更新分页，参数element传的是分页的容器

function addClickListener(element){
    element.children('ul').children('li').bind('click',function(){
        var temp = Number($(this).attr('value'));
        var pagenumber = Number($(this).parent().parent().attr('pagenumber'));
        var totalpage = Number($(this).parent().parent().attr('totalpage'));
        if(temp == 0){
            temp = pagenumber-1;
        }else if(temp == -1){
            temp = pagenumber+1;
        }
        if(temp != pagenumber && temp !=0 && temp<=totalpage){
            $(this).parent().parent().attr('pagenumber',temp);
            paginationClick(element.attr("id"));
            initPagination(element);
        }
        return false;
    })
}
function checkParamIsPositiveInteger(param){
    var reg = /^[1-9]+[0-9]*]*$/;
    return reg.test(param);
}

//用户需要自己实现的点击事件，参数为分页容器的id
function paginationClick(pagination_id){
    var pagenumber = $('#'+pagination_id+'').attr('pagenumber');
    var totalpage = $('#'+pagination_id+'').attr('totalpage');
    // console.log(temp);
    // console.log(pagenumber);
    JSON.stringify(pagenumber);
    $.ajax({
        type:"POST",
        url:constUrl+"ws/remote/blacklist/listpage",
        dataType:"json",
        data: {
            operateType: "showPaged",
            onePageCount: "10",
            currentPage: pagenumber
        },
        success:function(data){
            addBox(data.data);
        },
        error:function () {
            console.log(pagenumber);
        }
    });
}
function addBox(data){
    $("tr").remove(".addTr");
    console.log(data)
    for(var i=0;i<data.list.length;i++) {
    	var valid = data.list[i].valid;
    	var tmp = "";
    	var validStr = ""
    	if(valid){
    		tmp = "禁用";
    		validStr = "正在启用";
    	}else{
    		tmp = "启用";
    		validStr = "禁用";
    	}
        $("#hostGroupTableList").append(
            "<tr id="+data.list[i].id+" class='addTr'>" +
            "<td>"+(i+1)+"</td>"+
            "<td>"+data.list[i].appName+"</td>"+
            "<td title='"+data.list[i].valid+"'>"+validStr+"</td>"+
            "<td><div class=\"am-btn-toolbar\">"+
            "<div class=\"am-btn-group am-btn-group-xs \">"+
            "<button class=\"am-btn am-btn-default am-btn-xs am-text-success am-hide-sm-only\" onclick=\"stopuse("+data.list[i].id+","+data.list[i].valid+")\">"+
            "<span class=\"am-icon-pencil-square-o\"></span>"+tmp+"</button>"+
            "<button class=\"am-btn am-btn-default am-btn-xs am-text-secondary\" onclick=\"openalter("+data.list[i].id+")\">" +
            "<span class=\"am-icon-pencil-square-o\"></span> 修改</button>"+
            "<button class=\"am-btn am-btn-default am-btn-xs am-text-danger am-hide-sm-only\" onclick=\"infodelete("+data.list[i].id+")\">"+
            "<span class=\"am-icon-trash-o\"></span>删除</button>"+
            "</div></div></td>" +
            "</tr>"
        );
    }
}
function addSoftware() {
    layer.ready(function() {
        //官网欢迎页
        layer.open({
            type: 2,
            skin: 'layui-layer-lan',
            title: '添加黑名单',
            fix: false,
            shadeClose: true,
            maxmin: true,
            area: ['450px', '345px'],
            content:constUrl+'views/blacklist/add.action'
        });
    });
}

//弹出修改页面
function openalter(Id) {
    //页面一打开就执行，放入ready是为了layer所需配件（css、扩展模块）加载完毕
    // console.log(algorithmID);
    layer.ready(function() {
        //官网欢迎页
        layer.open({
            type: 2,
            skin: 'layui-layer-lan',
            title: '修改分组信息',
            fix: false,
            shadeClose: true,
            maxmin: true,
            area: ['450px', '345px'],
            content: constUrl+'views/blacklist/add.action?id='+Id
        });
    });
}

function stopuse(id,valid){
	
	var index = parent.layer.getFrameIndex(window.name);
    layer.confirm('确定要修改该黑名单可用性吗？', {
        btn: ['确定','取消'] //按钮
    }, function(){
        $.ajax({
            type:"POST",
            url:constUrl+"ws/remote/blacklist/update.action",
            dataType:"json",
            data: {
                id:id,
                valid:!valid
            },
            success:function(responseText){
                if(responseText.desc=="SUCCESS"){
                    layer.confirm('修改成功！',{
                        btn:['确定']
                    },function () {
                        parent.location.reload(index);
                        parent.layer.close(index);
                    })
                }
            },
            complete: function () {
            },
            error: function () {

            }
        })
    }, function(){
        layer.msg('取消删除', {
            time: 1000 //1s后自动关闭
        });
    });
    
}

// 删除列表内容
function infodelete(id){
    var index = parent.layer.getFrameIndex(window.name);
    layer.confirm('确定要删除该黑名单吗？', {
        btn: ['确定','取消'] //按钮
    }, function(){
        $.ajax({
            type:"GET",
            url:constUrl+"ws/remote/blacklist/remove.action",
            dataType:"json",
            data: {
                id:id
            },
            success:function(responseText){
                if(responseText.desc=="SUCCESS"){
                    layer.confirm('删除成功！',{
                        btn:['确定']
                    },function () {
                        parent.location.reload(index);
                        parent.layer.close(index);
                    })
                }
            },
            complete: function () {
            },
            error: function () {

            }
        })
    }, function(){
        layer.msg('取消删除', {
            time: 1000 //1s后自动关闭
        });
    });
}